package adim;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class AppScreen implements CommandListener, Runnable
{
	private Displayable _defaultDisplay;
	private Displayable _backupDisplay;

	private ConfirmDialog _cDialog;
	private ProgressDialog _pDialog;

	private Display _display;

	public Command _CMD_EXIT;
	
	public AppScreen(App app)
	{
		_CMD_EXIT = new Command("Cancel", Command.EXIT, 0);
		_defaultDisplay = null;
		//TODO: Is this the best way? Carrying around possibly-not-to-be-used but created objects?
		_cDialog = new ConfirmDialog(this);
		_pDialog = new ProgressDialog(this);
		_backupDisplay = app.getCurrentDisplay();
		_display = app.getDisplay();
	}


	protected void _exit()
	{
		_display.setCurrent(_backupDisplay);
	}

	protected void startBackgroundThread()
	{
		Thread t = new Thread(this);
		t.start();
	}

	protected void startBackgroundThread(String title, String msg)
	{
		_cDialog.setTitle(title);
		_cDialog.setMessage(msg);
		setCurrentDisplay(_cDialog.getDisplay());
	}

	public void backgroundThread()
	{
		_exit();
	}

	public void run() {
		_pDialog.setTitle("Progress");
		_pDialog.setMessage("Sending In Progress...");
		setCurrentDisplay(_pDialog.getDisplay());
		backgroundThread();
	}

	public void processCommands(Command c, Displayable s) {}

	public void commandAction(Command c, Displayable s)
	{
		if(c == _CMD_EXIT || c == _pDialog.CMD_OK ) {
			_exit();
		} else if (c == _cDialog.CMD_YES) {
			startBackgroundThread();
			return;
		} else if (c == _cDialog.CMD_BACK) {
			setCurrentDisplay(_defaultDisplay);
			return;
		}

		processCommands(c, s);
	}

	public void setDefaultDisplay(Displayable s)
	{
		_defaultDisplay = s;
	}

	public Displayable getDefaultDisplay()
	{
		return _defaultDisplay;
	}

	public void start()
	{
		_display.setCurrent(_defaultDisplay);
	}

	public void setCurrentDisplay(Displayable s)
	{
		_display.setCurrent(s);
	}

	public Displayable getCurrentDisplay()
	{
		return _display.getCurrent();
	}
}
